package com.emip.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.emip.bean.QuarterStoreBean;
import com.emip.dao.QuarterStoreDAO;


@Repository("quaterStoreDAO")
public class QuarterStoreDAOImpl extends StoreDAO implements QuarterStoreDAO {

	public List<QuarterStoreBean> getByTimespan(int startYear, 
			int startQuarter, int endYear, int endQuarter) {
		return this.getByTimespan(startYear, startQuarter, endYear, endQuarter, null, null);
	}

	@SuppressWarnings("unchecked")
	public List<QuarterStoreBean> getByTimespan(int startYear, 
			int startQuarter, int endYear, int endQuarter, String[] items, String siteId) {
		String hql = getQuarterHQL(startYear, startQuarter, endYear, endQuarter, items, siteId);
		hql += ", entity.item.id";
		return this.getHibernateTemplate().find(hql);
	}

	public QuarterStoreBean merge(QuarterStoreBean store) {
		return getHibernateTemplate().merge(store);
	}

	@SuppressWarnings("unchecked")
	public QuarterStoreBean findByQuarter(String year, String quarter, String siteId, String itemId) {
		List<QuarterStoreBean> quarters = 
				getHibernateTemplate().find("from QuarterStoreBean q where q.year = '" + year + "' and q.quater = '" + quarter + "' and q.site.id = '" + siteId + "' and q.item.id = '" + itemId + "'");
		if (quarters != null && quarters.size() > 0) {
			return quarters.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public long getCount(int startYear, int startQuarter, int endYear,
			int endQuarter, String[] items, String siteId) {
		String hql = "select distinct entity.year, entity.quater " + 
			getQuarterHQL(startYear, startQuarter, endYear, endQuarter, items, siteId);
		List<Object> objs = getHibernateTemplate().find(hql);
		if (objs != null) return objs.size();
		return 0;
	}

	public List<QuarterStoreBean> getByTimespan(int startYear,
			int startQuarter, int endYear, int endQuarter, String[] items,
			String siteId, int page, int size) {
		return this.getThPage(QuarterStoreBean.class, "quater", startYear, startQuarter, endYear, endQuarter, items, siteId, page, size);
	}
	
	public Object[] getStatistics(int startYear, int startQuarter, 
			int endYear, int endQuarter, String itemIds, String siteId) {
		long count = this.getCount(startYear, startQuarter, endYear, endQuarter, new String[]{itemIds}, siteId);
		if (count == 0) return null;
		String[] result = this.getThStatistic("Quarter", "quater", startYear, startQuarter, endYear, endQuarter, new String[]{itemIds}, siteId);
		result[3] = Integer.parseInt(result[3])*100/count + "%";
		return result;
	}

}
